import CryptoJS from 'crypto-js';

let defaultKey = 'syausnsoftsnsoft';

function getAesString(data, key, iv) { // 加密
  var keyp = CryptoJS.enc.Utf8.parse(key);
  var ivp = CryptoJS.enc.Utf8.parse(iv);
  var encrypted = CryptoJS.AES.encrypt(data, keyp,
    {
      iv: ivp,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  return encrypted.toString(); // 返回的是base64格式的密文
}
function getDAesString(encrypted, key, iv) { // 解密
  var keyp = CryptoJS.enc.Utf8.parse(key);
  var ivp = CryptoJS.enc.Utf8.parse(iv);
  var decrypted = CryptoJS.AES.decrypt(encrypted, keyp,
    {
      iv: ivp,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

export default {
  AES: (data, k) => { // 加密
    var key = k || defaultKey; // 密钥
    var iv = '1234567812345678';
    var encrypted = getAesString(data, key, iv); // 密文
    return encrypted;
  },
  DAES: (data, k) => { // 解密
    var key = k || defaultKey; // 密钥
    var iv = '1234567812345678';
    var decryptedStr = getDAesString(data, key, iv);
    return decryptedStr;
  }
}
